<template>
  <div id="addQuestionView">
    <a-card class="outer-card" :bordered="false">
      <a-card
        class="content-card"
        :title="updatePage ? '更新题目' : '创建题目'"
        :bordered="true"
        :header-style="{ background: '#f5f5f5', fontWeight: 'bold' }"
      >
        <a-form :model="form" layout="vertical">
          <!-- 基本信息区域 -->
          <div class="form-section">
            <h3 class="section-title">基本信息</h3>
            <a-form-item label="标题" required>
              <a-input
                v-model="form.title"
                placeholder="请输入题目标题"
                allow-clear
              />
            </a-form-item>

            <a-form-item label="标签">
              <a-select
                v-model="form.tags"
                placeholder="请选择标签"
                allow-clear
              >
                <a-option value="算法">算法</a-option>
                <a-option value="数据库">数据库</a-option>
                <a-option value="前端">前端</a-option>
                <a-option value="后端">后端</a-option>
                <a-option value="测试">测试</a-option>
              </a-select>
            </a-form-item>

            <a-form-item label="题目内容" required>
              <MdEditor
                :value="form.content"
                :handle-change="onContentChange"
              />
            </a-form-item>

            <a-form-item label="参考答案">
              <MdEditor :value="form.answer" :handle-change="onAnswerChange" />
            </a-form-item>
          </div>

          <!-- 判题配置区域 -->
          <div class="form-section">
            <h3 class="section-title">判题配置</h3>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="时间限制 (ms)" required>
                  <a-input-number
                    v-model="form.judgeConfig.timeLimit"
                    min="0"
                    style="width: 100%"
                    placeholder="如：1000"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="内存限制 (KB)" required>
                  <a-input-number
                    v-model="form.judgeConfig.memoryLimit"
                    min="0"
                    style="width: 100%"
                    placeholder="如：1000"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="堆栈限制 (KB)" required>
                  <a-input-number
                    v-model="form.judgeConfig.stackLimit"
                    min="0"
                    style="width: 100%"
                    placeholder="如：1000"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>

          <!-- 测试用例配置区域 -->
          <div class="form-section">
            <div class="section-header">
              <h3 class="section-title">测试用例配置</h3>
              <a-button type="primary" size="small" @click="handleAdd">
                <template #icon><icon-plus /></template>
                添加用例
              </a-button>
            </div>
            <div class="cases-container">
              <a-collapse accordion>
                <a-collapse-item
                  v-for="(caseItem, index) in form.judgeCase"
                  :key="index"
                  :header="`测试用例 ${index + 1}`"
                >
                  <a-space direction="vertical" style="width: 100%">
                    <a-form-item
                      label="输入"
                      :key="'input-' + index"
                      class="no-margin-bottom"
                    >
                      <a-textarea
                        v-model="caseItem.input"
                        placeholder="请输入测试输入用例"
                        allow-clear
                        :auto-size="{ minRows: 3, maxRows: 6 }"
                      />
                    </a-form-item>
                    <a-form-item
                      label="期望输出"
                      :key="'output-' + index"
                      class="no-margin-bottom"
                    >
                      <a-textarea
                        v-model="caseItem.output"
                        placeholder="请输入测试输出用例"
                        allow-clear
                        :auto-size="{ minRows: 3, maxRows: 6 }"
                      />
                    </a-form-item>
                    <div class="delete-button-container">
                      <a-popconfirm
                        content="确认删除此测试用例？"
                        @ok="handleDelete(index)"
                      >
                        <a-button status="danger" type="outline" size="small">
                          <template #icon><icon-delete /></template>
                          删除此用例
                        </a-button>
                      </a-popconfirm>
                    </div>
                  </a-space>
                </a-collapse-item>
              </a-collapse>
            </div>
          </div>

          <!-- 提交按钮区域 -->
          <div class="form-footer">
            <a-space>
              <a-button type="secondary">取消</a-button>
              <a-button type="primary" @click="doSubmit" :loading="submitting">
                {{ updatePage ? "更新题目" : "提交题目" }}
              </a-button>
            </a-space>
          </div>
        </a-form>
      </a-card>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";
import { IconPlus, IconDelete } from "@arco-design/web-vue/es/icon";

const route = useRoute();
const router = useRouter();
const updatePage = ref(route.path.includes("update"));
const submitting = ref(false);

let form = ref({
  title: "",
  tags: "",
  answer: "",
  content: "",
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 1000,
    timeLimit: 1000,
  },
  judgeCase: [{ input: "", output: "" }],
});

const loadData = async () => {
  const id = route.query.id;
  if (!id) return;
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    id as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    // 修复类型错误，检查是否需要解析
    if (typeof form.value.judgeCase === "string") {
      form.value.judgeCase = JSON.parse(form.value.judgeCase);
    } else if (!form.value.judgeCase) {
      form.value.judgeCase = [{ input: "", output: "" }];
    }
    if (typeof form.value.judgeConfig === "string") {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig);
    } else if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,
      };
    }
    if (typeof form.value.tags === "string") {
      form.value.tags = JSON.parse(form.value.tags);
    } else if (!form.value.tags) {
      form.value.tags = [];
    }
    // 如果tags是数组且只有一个元素，则使用该元素作为当前选中的标签
    if (Array.isArray(form.value.tags) && form.value.tags.length > 0) {
      form.value.tags = form.value.tags[0];
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};

onMounted(() => loadData());

const doSubmit = async () => {
  if (!form.value.title) {
    message.warning("请输入题目标题");
    return;
  }
  if (!form.value.content) {
    message.warning("请输入题目内容");
    return;
  }
  // 将选中的标签转换为数组
  const submitData = {
    ...form.value,
    tags: form.value.tags ? [form.value.tags] : [],
  };
  submitting.value = true;
  try {
    const res = updatePage.value
      ? await QuestionControllerService.updateQuestionUsingPost(submitData)
      : await QuestionControllerService.addQuestionUsingPost(submitData);
    if (res.code === 0) {
      message.success(updatePage.value ? "更新成功" : "创建成功");
      router.push("/question/list");
    } else {
      message.error("提交失败，" + res.message);
    }
  } catch (error) {
    message.error("提交出错: " + error);
  } finally {
    submitting.value = false;
  }
};

const handleAdd = () => form.value.judgeCase.push({ input: "", output: "" });
const handleDelete = (index: number) => {
  if (form.value.judgeCase.length <= 1) {
    message.warning("至少需要保留一个测试用例");
    return;
  }
  form.value.judgeCase.splice(index, 1);
};
const onContentChange = (value: string) => (form.value.content = value);
const onAnswerChange = (value: string) => (form.value.answer = value);
</script>

<style scoped>
#addQuestionView {
  min-height: 100vh;
  padding: 20px 0;
  background-color: #f5f7fa;
}

.outer-card {
  margin: 0 auto;
  max-width: 900px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  background-color: #fff;
}

.content-card {
  border-radius: 4px;
}

.form-section {
  margin-bottom: 32px;
  padding: 24px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.section-title {
  color: #333;
  font-weight: 600;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 4px solid #165dff;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cases-container {
  width: 100%;
  overflow: visible;
}

.no-margin-bottom {
  margin-bottom: 12px;
}

.delete-button-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 折叠面板样式优化 */
:deep(.arco-collapse-item-header) {
  background-color: #f5f7fa;
  border-radius: 4px;
  font-weight: 500;
}

:deep(.arco-collapse-item) {
  margin-bottom: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.arco-textarea-wrapper) {
  border-radius: 4px;
}

:deep(.arco-input-wrapper),
:deep(.arco-input-tag) {
  border-radius: 4px;
}

:deep(.arco-btn) {
  border-radius: 4px;
}
</style>
